define(['angularAMD'], function (angularAMD) {
    angularAMD.service('favouriteService', ['$rootScope', 'config', 'MMWService',
    function($rootScope, config, $MMWService){
        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        // 20220727 modify by Alan for#107965 : 處理oracle空陣列為null的情境
        const favourite_homepage_info_get = (userNo, callback) => {
            const content = {
                UserNo: userNo
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.favourite_homepage_info_get',
                content: content,
                success: (data) => {
                    data = respParser(data);
                    callback && callback(data);
                }
            });
        }

        const favourite_homepage_process = (option, callback) => {
            const content = option;
            if(Array.isArray(option.FavouriteList)) {
                option.FavouriteList = option.FavouriteList.join(',');
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.favourite_homepage_process',
                content: content,
                success: (data) => {
                    data = respParser(data);
                    callback && callback(data);
                }
            });
        }

        const respParser = (data) => {
            // Oracle的空字串會回傳null，偵測value是null就轉成空字串
            Object.keys(data).forEach(prop => {
                if(data[prop] === null) {
                    data[prop] = '';
                }
            })
            // FavouriteList後端傳回string，轉成陣列比較好處理
            if(typeof data.FavouriteList === 'string') {
                if(data.FavouriteList === '') {
                    data.FavouriteList = [];
                } else {
                    data.FavouriteList = data.FavouriteList.split(',');
                }
            }

            return data;
        }
        
        this.get = (userNo, callback) => {
            favourite_homepage_info_get(userNo, callback);
        }


        this.setFavouriteList = (option, callback) => {
            option.TYPE = 1;
            favourite_homepage_process(option, callback);
        }

        this.setDefaultProgram = (option, callback) => {
            option.TYPE = 3;
            favourite_homepage_process(option, callback);
        }
        
        return this;
    }]);
});

